package vn.gq.app4vn.doctruyen;

import vn.gq.cd.adutils.AdHelper;
import vn.gq.cd.model.bean.AdmobItem;
import vn.gq.cd.model.bean.CategoryItem;
import vn.gq.cd.view.ChapterFragment;
import vn.gq.tym.utils.IClientListener;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.LinearLayout;

public class ChapterActivity extends BaseActivity implements IClientListener {

	private AdHelper mAdsHandler;
	private Handler mHandler = new Handler();
	private CategoryItem mCatItem;

	private Runnable showDialogRunnable = new Runnable() {
		
		@Override
		public void run() {
			new BookmarkManager(ChapterActivity.this).showDialogConfirm();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_layout);
		mCatItem = getIntent().getExtras().getParcelable("DATA");
		// Setup Admob Ads
		LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
		AdmobItem aUnitId = AdmobItem.load(getApplicationContext());
		if (BuildConfig.DEBUG) {
			Log.e("longhoanggiang", "ad = "+aUnitId.getAdTypeBanner());
		}
		AdView adView = new AdView(this, AdSize.SMART_BANNER, aUnitId.getAdTypeBanner());
		adLayout.addView(adView);
		mAdsHandler = new AdHelper(this, adView);
		if (!getString(R.string.author).equals("")) {
			getSupportActionBar().setSubtitle(getString(R.string.author));
		}
		ChapterFragment fragment = ChapterFragment.newInstance(mCatItem, new BookmarkManager(this).getBookmarkChapterPos());
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.add(fragment.getContainerId(), fragment, fragment.getFragmentTag()).commit();
	}
	
	public static void startActivity(Context context, CategoryItem cat) {
		Intent intent = new Intent(context, ChapterActivity.class);
		intent.putExtra("DATA", cat);
		context.startActivity(intent);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mAdsHandler.loadAd();
	}

	@Override
	protected void onStop() {
		super.onStop();
		mAdsHandler.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mAdsHandler.onDestroy();
	}

	@Override
	public void onDone(int code, Object result) {
		if (!Configuration.MULTI_STORIES_APP) {
			mHandler.postDelayed(showDialogRunnable, 100);
		}
	}

}
